﻿#include"SeqList.h"
#include"Contact.h"
#include<string.h>

void LoadContact(Contact* con) {
	FILE* pf = fopen("contact.txt", "rb");
	if (pf == NULL) {
		perror("fopen error!\n");
		return;
	}
	//循环读取⽂件数据
	peoinfo info;
	while (fread(&info, sizeof(peoinfo), 1, pf))
	{
		SLPushBack(con, info);
	}
	printf("历史数据导⼊通讯录成功！\n");
}

void ContactInit(Contact* con)
{
	SLInit(con);
	LoadContact(con);
}

void ContactDestroy(Contact* con)
{
	SaveContact(con);
	SLDestroy(con);
}

void ContactAdd(Contact* con) {
	peoinfo info;
	printf("请输入姓名：\n");
	scanf("%s", &info.name);
	printf("请输⼊性别：\n");
	scanf("%s", &info.gender);
	printf("请输⼊年龄：\n");
	scanf("%d", &info.age);
	printf("请输⼊联系电话：\n");
	scanf("%s", &info.tel);
	printf("请输⼊地址：\n");
	scanf("%s", &info.addr);
	SLPushBack(con, info);
	printf("插⼊成功！\n");
}

int FindByName(Contact* con, char name[])
{
	
	
	for (int i = 0; i < con->size - 1; i++)
	{
		if (0 == strcmp(name, con->arr[i].name))
			return i;
		return -1;
	}
}

void ContactDel(Contact* con)
{
	char name[NAME_MAX];
	printf("请输入要删除的联系人姓名\n");
	scanf("%s", name);
	int find = FindByName(con, name);
	if (find != 0)
	{
		printf("未找到联系人，删除失败\n");
		return;
	}
	SLErase(con, find);
	printf("删除成功\n");
}

void ContactFind(Contact* con)
{
	char name[NAME_MAX];
	printf("请输入你要查找的联系人姓名：");
	scanf("%s", name);
	int i = FindByName(con, name);
	if (i < 0)
	{
		printf("未找到你要查找的联系人姓名！");
		return;
	}
	printf("查找成功！");
	printf("%-10s %-6s %-3d  %-20s %-20s\n", con->arr[i].name, con->arr[i].gender, con->arr[i].age, con->arr[i].tel, con->arr[i].addr);

}

void ContactModify(Contact* con)
{
	char name[NAME_MAX];
	printf("请输入要修改的人的姓名\n");
	scanf("%s", name);
	int pos = FindByName(con, name);
	if (pos != 0)
	{
		printf("未找到联系人，修改失败\n");
		return;
	}
	printf("请输入修改后的联系人姓名：\n");
	scanf("%s", con->arr[pos].name);
	printf("请输入修改后的联系人性别：\n");
	scanf("%s", con->arr[pos].gender);
	printf("请输入修改后的联系人年龄：\n");
	scanf("%d", &con->arr[pos].age);
	printf("请输入修改后的联系人电话：\n");
	scanf("%s", con->arr[pos].tel);
	printf("请输入修改后的联系人住址：\n");
	scanf("%s", con->arr[pos].addr);
}
void ContactShow(Contact* con)
{
	printf("%-10s %-6s %-3s %-20s %-20s\n", "姓名","性别", "年龄", "电话", "住址");
	for (int i = 0; i < con->size;i++)
	{
		printf("%-10s %-6s %-3d  %-20s %-20s\n", con->arr[i].name, con->arr[i].gender, con->arr[i].age, con->arr[i].tel, con->arr[i].addr);
	}
}

void SaveContact(Contact* con) {
	FILE* pf = fopen("contact.txt", "wb");
	if (pf == NULL) {
		perror("fopen error!\n");
		return;
	}
	//将通讯录数据写⼊⽂件
	for (int i = 0; i < con->size; i++)
	{
		fwrite(con->arr + i, sizeof(peoinfo), 1, pf);
	}
	printf("通讯录数据保存成功！\n");
}
